import React, { Component } from "react";
import {
  Row,
  Col,
  Card,
  Input,
  Select,
  Button,
  Table,
  Form,
  message,
  Popconfirm,
  Modal
} from "antd";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { connect } from "dva";
import { pagination, dateFormat } from "@/utils/utils";
import router from "umi/router";
import { debounce } from "debounce";
import styles from "./index.less";

const { Option } = Select;

@connect(({ global, jobManage }) => ({
  zbJobUser: jobManage.zbJobUser,
  industryList: global.industryList,
  industryPositionList: global.industryPositionList
}))
class User extends Component {
  static defaultProps = {
    industryList: [],
    industryPositionList: []
  };
  constructor(props) {
    super(props);
    this.searchZbJobUser = debounce(this.searchZbJobUser, 600);
    this.state = {
      checkModalVisible: false,
      taskDescription: null,
      setPagination: {
        ...pagination
      },
      searchParams: {
        search: "",
        industryId: "",
        positionId: ""
      }
    };
    this.columns = [
      {
        title: "任务简述",
        dataIndex: "title",
        align: "center"
      },
      {
        title: "行业",
        dataIndex: "industryName",
        align: "center"
      },
      {
        title: "项目内容",
        dataIndex: "positionName",
        align: "center"
      },
      {
        title: "发布公司",
        dataIndex: "companyName",
        align: "center"
      },
      {
        title: "预算",
        dataIndex: "budgetInfo",
        align: "center"
      },
      {
        title: "任务描述",
        dataIndex: "description",
        align: "center",
        render: (text, record) => (
          <span>
            <a
              onClick={() => {
                this.handleCheck(true, text);
              }}
            >
              查看
            </a>
          </span>
        )
      },
      {
        title: "发布时间",
        dataIndex: "createTime",
        align: "center",
        sorter: (a, b) => Date.parse(a.createTime) - Date.parse(b.createTime),
        render: text => {
          return dateFormat(text);
        }
      },
      {
        title: "费用管理",
        align: "center",
        render: record => {
          return (
            <Button
              type="link"
              onClick={() =>
                router.push({
                  pathname: "/taskManagement/fees",
                  state: record
                })
              }
            >
              查看
            </Button>
          );
        }
      },
      {
        title: "操作",
        align: "center",
        fixed: "right",
        width: 220,
        render: (text, record, index) => (
          <span className={styles.operation}>
            <a
              onClick={() =>
                router.push({
                  pathname: "/taskManagement/updateJob/false",
                  state: record
                })
              }
            >
              编辑
            </a>
            <a
              onClick={() => {
                router.push({
                  pathname: "/taskManagement/userManage",
                  state: { jobId: record.id, title: record.title }
                });
              }}
            >
              承揽方管理
            </a>
            <Popconfirm
              title={`确认删除该条任务”？`}
              onConfirm={async () => {
                await this.handleRemove(record, index);
                // action.reload();
              }}
              // onCancel={cancel}
              okText="确定"
              cancelText="取消"
            >
              <a href="#">删除</a>
            </Popconfirm>
          </span>
        )
      }
    ];
  }

  componentDidMount() {
    this.getIndustryList();
    this.searchZbJobUser();
  }

  changeInput = async val => {
    const { searchParams } = this.state;
    this.setState({
      searchParams: {
        ...searchParams,
        search: val
      }
    });
    this.searchZbJobUser();
  };

  getIndustryPositionList = async industryId => {
    await this.props.dispatch({
      type: "global/getIndustryPositionList",
      payload: industryId
    });
  };

  getIndustryList = () => {
    this.props.dispatch({
      type: "global/getIndustryList"
    });
  };

  searchZbJobUser = () => {
    const { searchParams, setPagination } = this.state;
    const pagination = {
      page: setPagination.current,
      size: setPagination.pageSize
    };
    this.props.dispatch({
      type: "jobManage/searchZbJobUser",
      payload: { searchParams, pagination }
    });
  };

  // 页码切换
  handlePageChange = current => {
    const { setPagination } = this.state;
    this.setState({
      setPagination: {
        ...setPagination,
        current
      }
    });
    this.searchZbJobUser();
  };

  // 每页/条 切换
  handleSizeChange = (current, pageSize) => {
    const { setPagination } = this.state;
    this.setState({
      setPagination: {
        ...setPagination,
        current,
        pageSize
      }
    });
    this.searchZbJobUser();
  };

  handleCheck = (flag, taskDescription = {}) => {
    this.setState({
      checkModalVisible: flag,
      taskDescription
    });
  };

  handleChangeSelect = async (state, val) => {
    const { searchParams } = this.state;
    const states = { [state]: val };
    this.setState({
      searchParams: {
        ...searchParams,
        ...states
      }
    });
    if (state == "industryId") {
      this.setState({
        searchParams: {
          ...searchParams,
          ...states,
          positionId: ""
        }
      });
      if (val) {
        this.getIndustryPositionList({ ...states });
      }
    }
    this.searchZbJobUser();
  };

  // selectTable = async () => {
  //   console.log('selectTable')
  // }

  handleRemove = async (selectedRows, index) => {
    const hide = message.loading("正在删除");
    if (!selectedRows) return true;
    await this.props.dispatch({
      type: "jobManage/deleteZbJob",
      payload: {
        jobId: selectedRows.id,
        index: 1
      }
    });
    hide();
    message.success("删除成功，即将刷新");
  };

  render() {
    const { zbJobUser, industryList, industryPositionList } = this.props;
    const {
      setPagination,
      checkModalVisible,
      taskDescription,
      searchParams
    } = this.state;

    const pagination = {
      ...setPagination,
      total: zbJobUser.totalElements,
      showTotal: count => `总共 ${count} 条`,
      onShowSizeChange: this.handleSizeChange,
      onChange: this.handlePageChange
    };
    return (
      <PageHeaderWrapper className={styles.userContainer}>
        <Card bordered={false} className="marginB24">
          <Row type="flex" justify="space-between">
            <Col>
              <Input
                allowClear
                onChange={e => this.changeInput(e.target.value)}
                value={searchParams.search}
                placeholder="任务简述/发布公司"
                style={{ width: 200 }}
                className="marginR"
              />
              行业：
              {
                <Select
                  value={searchParams.industryId}
                  allowClear
                  style={{ width: 200 }}
                  className="marginR"
                  onChange={v => this.handleChangeSelect("industryId", v)}
                  placeholder="请选择行业"
                >
                  {industryList &&
                    industryList.map(item => (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    ))}
                </Select>
              }
              项目内容：
              {
                <Select
                  value={searchParams.positionId}
                  allowClear
                  style={{ width: 200 }}
                  onChange={v => this.handleChangeSelect("positionId", v)}
                  placeholder="请选择项目内容"
                >
                  {industryPositionList.map(item => (
                    <Option key={item.id} value={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              }
            </Col>
            <Col>
              {/* <Button type="primary" icon="search" className="marginR" onClick={this.selectTable} >搜索</Button> */}
              <Button
                type="primary"
                icon="plus"
                onClick={() => router.push(`/taskManagement/createJob/true`)}
              >
                新增任务
              </Button>
            </Col>
          </Row>
        </Card>

        <div className="wrapperClass">
          <Table
            rowKey="id"
            scroll={{ x: 1200 }}
            columns={this.columns}
            dataSource={zbJobUser.content}
            pagination={pagination}
          />
        </div>

        <Modal
          destroyOnClose
          title="任务描述"
          visible={checkModalVisible}
          onCancel={() => this.handleCheck(false)}
          footer={[
            <Button
              key="submit"
              type="primary"
              onClick={() => this.handleCheck(false)}
            >
              关闭
            </Button>
          ]}
        >
          <p>{taskDescription}</p>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create()(User);
